package org.jssvc.opac.adapter

import android.util.Log
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import cn.bingoogolapple.baseadapter.BGARecyclerViewAdapter
import cn.bingoogolapple.baseadapter.BGAViewHolderHelper
import com.bumptech.glide.Glide
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import org.json.JSONObject
import org.jssvc.opac.R
import org.jssvc.opac.bean.Content
import org.jssvc.opac.data.Constant

class BookAdapter(recyclerView: RecyclerView) :
    BGARecyclerViewAdapter<Content>(recyclerView, R.layout.item_search_book) {

    override fun setItemChildListener(helper: BGAViewHolderHelper?, viewType: Int) {
        helper?.setItemChildClickListener(R.id.iv_book_store)
    }

    override fun fillData(helper: BGAViewHolderHelper, position: Int, model: Content) {
        helper.setText(R.id.book_name, model.title)
        helper.setText(R.id.book_author, model.author)
        helper.setText(R.id.book_callNo, model.callNo)

        var imageCover = helper.getView<ImageView>(R.id.book_cover)

        // 获取封面
        OkGo.get<String>(Constant.api_book_cover)
            .params("marc_no", model.marcRecNo)
            .params("isbn", model.isbn)
            .params("rdm", 0) // 随机数
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    var jo = JSONObject(response?.body())

                    var coverUrl = jo.optString("image")
                    var lendAvl = jo.optString("lendAvl")
                    Log.d("DHY__", "cover_url = $coverUrl")
                    Log.d("DHY__", "lendAvl = $lendAvl")

                    Glide.with(helper.convertView.context).load(coverUrl)
                        .placeholder(R.drawable.ic_book_cover)
                        .error(R.drawable.ic_book_cover)
                        .into(imageCover)
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                }
            })
    }
}